package com.tengfei.blogsystem.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version v1.0
 * @author} feige
 * @date 2021-10-18-15:29
 * @description
 */
public class CookieUtils {

    // 设置根路径
    public static final String DOMAIN = "localhost";
    // 设置有效时间为180天
    public static final int LIFE_CYCLE = 60 * 60 * 24 * 180;

    /**
     * 设置cookie
     *
     * @param response
     * @param key
     * @param value
     */
    public static void setUpCookie(HttpServletResponse response, String key, String value) {
        setUpCookie(response, key, value, LIFE_CYCLE);
    }

    /**
     * 设置cookie+生命周期
     *
     * @param response
     * @param key
     * @param value
     * @param lifeCycle
     */
    public static void setUpCookie(HttpServletResponse response, String key, String value, int lifeCycle) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setDomain(DOMAIN);
        cookie.setMaxAge(lifeCycle);
        response.addCookie(cookie);
    }

    /**
     * 获取cookie
     *
     * @param request
     * @param key
     * @return
     */
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 清除cookie
     *
     * @param response
     * @param key
     */
    public static void deleteCookie(HttpServletResponse response, String key) {
        setUpCookie(response, key, "", 0);
    }
}
